package com.hoshiicloud.withdraw.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.withdraw.entity.UserBank3RealCheck;
import com.hoshiicloud.withdraw.mapper.UserBank3RealCheckMapper;
import com.hoshiicloud.withdraw.param.Bank3RealCheckParam;
import com.hoshiicloud.withdraw.service.UserBank3RealCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * (UserBank3RealCheck)表服务实现类
 *
 * @author makejava
 * @since 2019-08-30 15:33:49
 */
@Service("userBank3RealCheckService")
@Slf4j
public class UserBank3RealCheckServiceImpl extends ServiceImpl<UserBank3RealCheckMapper, UserBank3RealCheck> implements UserBank3RealCheckService {

	private static final String host = "https://bankali.market.alicloudapi.com";
	private static final String path = "/bank3RealCheck";
	private static final String appcode = "3fb08054b979418cac4c9263503f1091";

	@Autowired
	protected UserBank3RealCheckMapper userBank3RealCheckMapper;


	@Override
	public JSONObject bank3RealCheck(Bank3RealCheckParam param) {
		JSONObject jsonObject = new JSONObject();
		try {
			Map<String, String> map = userBank3RealCheckMapper.bank3RealCheck(param);
			if (map == null || map.get("status") == null) {
				String response = HttpRequest.get(host + path)
						.header("Authorization", "APPCODE " + appcode)
						.form(BeanUtil.beanToMap(param)).execute().body();
				jsonObject = JSONUtil.parseObj(response);
				// 回写数据库
				if (!"01".equals(jsonObject.getStr("status"))) {
					UserBank3RealCheck.builder().bankAccount(param.getAccountNo())
							.name(param.getName())
							.createTime(new Date()).updateTime(new Date())
							.status("0").idcard(param.getIdCard()).msg(jsonObject.getStr("msg")).build().insert();
				} else {
					UserBank3RealCheck.builder().bankAccount(param.getAccountNo())
							.name(param.getName())
							.createTime(new Date()).updateTime(new Date())
							.status("1").idcard(param.getIdCard()).build().insert();
				}
				return jsonObject;
			} else if ("1".equals(map.get("status"))) {
				jsonObject.put("status", "01");
				jsonObject.put("msg", "验证通过");
				return jsonObject;
			} else if ("0".equals(map.get("status"))) {
				jsonObject.put("status", "02");
				jsonObject.put("msg", map.get("msg"));
				return jsonObject;
			}
		} catch (Exception e) {
			log.info("调用三要素验证失败", e);
			jsonObject.put("status", "02");
			jsonObject.put("msg", "调用验证接口失败");
		}
		return jsonObject;
	}
}